from typing import Dict, Any, Optional, Union
from flask import jsonify
from utils.logger import error, critical

class APIException(Exception):
    """API异常基类，用于规范化API错误响应
    
    所有API相关的自定义异常都应该继承此类
    """
    
    def __init__(self, message: str, code: int = 400, 
                 error_code: str = "BAD_REQUEST", 
                 details: Optional[Dict[str, Any]] = None):
        """初始化API异常
        
        Args:
            message: 错误消息
            code: HTTP状态码
            error_code: 业务错误代码
            details: 错误详情
        """
        self.message = message
        self.code = code
        self.error_code = error_code
        self.details = details or {}
        super().__init__(self.message)
    
    def to_dict(self) -> Dict[str, Any]:
        """将异常转换为字典，用于JSON响应
        
        Returns:
            Dict: 异常信息字典
        """
        return {
            "status": "error",
            "error_code": self.error_code,
            "message": self.message,
            "details": self.details
        }
    
    def to_response(self):
        """将异常转换为Flask响应
        
        Returns:
            Response: Flask响应对象
        """
        return jsonify(self.to_dict()), self.code


class ValidationError(APIException):
    """数据验证错误"""
    
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(
            message=message,
            code=400,
            error_code="VALIDATION_ERROR",
            details=details
        )


class AuthenticationError(APIException):
    """认证错误"""
    
    def __init__(self, message: str = "认证失败"):
        super().__init__(
            message=message,
            code=401,
            error_code="AUTHENTICATION_ERROR"
        )


class AuthorizationError(APIException):
    """授权错误"""
    
    def __init__(self, message: str = "没有操作权限"):
        super().__init__(
            message=message,
            code=403,
            error_code="AUTHORIZATION_ERROR"
        )


class ResourceNotFoundError(APIException):
    """资源不存在错误"""
    
    def __init__(self, resource_type: str, resource_id: Union[str, int]):
        super().__init__(
            message=f"{resource_type} ID:{resource_id} 不存在",
            code=404,
            error_code="RESOURCE_NOT_FOUND",
            details={
                "resource_type": resource_type,
                "resource_id": resource_id
            }
        )


class ServerError(APIException):
    """服务器内部错误"""
    
    def __init__(self, message: str = "服务器内部错误", exc_info: Optional[Exception] = None):
        # 记录详细错误日志
        if exc_info:
            critical(f"服务器错误: {message}", exc_info=True)
        else:
            critical(f"服务器错误: {message}")
            
        super().__init__(
            message=message,
            code=500,
            error_code="SERVER_ERROR"
        )


class DatabaseError(APIException):
    """数据库错误"""
    
    def __init__(self, message: str = "数据库操作失败", exc_info: Optional[Exception] = None):
        # 记录详细错误日志
        if exc_info:
            error(f"数据库错误: {message}", exc_info=True)
        else:
            error(f"数据库错误: {message}")
            
        super().__init__(
            message=message,
            code=500,
            error_code="DATABASE_ERROR"
        )


class ExternalServiceError(APIException):
    """外部服务错误"""
    
    def __init__(self, service_name: str, message: str, exc_info: Optional[Exception] = None):
        # 记录详细错误日志
        if exc_info:
            error(f"外部服务 {service_name} 错误: {message}", exc_info=True)
        else:
            error(f"外部服务 {service_name} 错误: {message}")
            
        super().__init__(
            message=f"外部服务 {service_name} 错误: {message}",
            code=502,
            error_code="EXTERNAL_SERVICE_ERROR",
            details={"service": service_name}
        )